<?php

namespace Apps\Pay\Controllers;

use AliPay\Pay;
use Apps\Common\Enum\PayState;
use Apps\Common\Enum\PayType;

class AlipayController extends BaseController
{
    private $alipayConfig;
    public function initialize()
    {
        $this->view->disable();
        $payConfig = include APP_COMMON_PATH . "base-config/pay.php";
        $this->alipayConfig = $payConfig['alipay'];
    }

    public function notifyAction()
    {
        $pay = new Pay($this->alipayConfig);
        $checkResult = $pay->notifyVerify();
        $echoResult = function($success, $msg='OK'){
            $result = $success ? 'success' : 'fail';
            echo $result;
        };
        if(is_int($checkResult)) {
            // 错误处理,
            // 100-xml解析异常，101-签名验证失败，102-返回状态码错误，103-业务结果异常
            switch($checkResult) {
                case PayState::REQUEST_TYPE_ERROR:
                    $echoResult(false, 'not post request');
                    break;
                case PayState::ASYNC_FAIL_SIGN:
                    $echoResult(false, 'sign verify error');
                    break;
                case PayState::REQUEST_ERROR:
                    $echoResult(false);
                    break;
            }
            $this->savePayLog(0, 0, PayType::ALIPAY, $checkResult, $_POST);
            return;
        }
        $transactionId = $_POST['trade_no'];
        $outTradeNo = $_POST['out_trade_no'];
        // 拆分订单号
        $outTradeNoArr = explode('-', $outTradeNo);
        $outTradeNo = $outTradeNoArr[0];
        $totalFee = intval(floatval($_POST['total_fee']) * 100);

        if(!in_array($_POST['trade_status'], ['TRADE_FINISHED', 'TRADE_SUCCESS'])) {
            $this->savePayLog($outTradeNo, $transactionId, PayType::ALIPAY, PayState::NOT_HANDLE, $_POST);
            $echoResult(true);
            return;
        }

        $this->payHandle($echoResult, PayType::ALIPAY, $transactionId, $outTradeNo, $totalFee, $_POST);
    }
}
